import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import { Form, Icon, Button, message, Spin, Modal, Table, Tooltip } from 'antd';
import moment from 'moment';
import { useUpdateEffect } from '@umijs/hooks';
import request from '@/utils/request';
import AddForm from './AddForm';
import Flow2 from '@/pages/FormDesigner/templates/Flow2.js';
import styles from '../styles.less';

const cellStyle = {
  maxWidth: 300,
  overflow: 'hidden',
  whiteSpace: 'nowrap',
  textOverflow: 'ellipsis',
  cursor: 'pointer',
};

const namespace = 'formManage';

function FormInfo(props) {
  const addFormEl = useRef();

  const [loading, setLoading] = useState(false);

  // 保存每次请求回填表单值
  const [formData, setFormData] = useState([]);

  // 表单/表单版本Modal标题
  const [formAddTitle, setFormAddTitle] = useState('新增表单');

  useEffect(() => {
    if (props.formAddType === 'addForm') {
      setFormAddTitle('新增表单');
    } else if (props.formAddType === 'editForm') {
      setFormAddTitle('修改表单');
    } else if (props.formAddType === 'addVersion') {
      setFormAddTitle('新增表单版本');
    } else if (props.formAddType === 'editVersion') {
      setFormAddTitle('修改表单版本');
    }
  }, [props.formAddType]);
  // 当dva:catalogId 变化的时候进行异步请求回填表单
  useUpdateEffect(() => {
    saveSelectForm({});
    saveFormButton(false);
    if (props.selectCatalog && props.selectCatalog.catalogId) {
      queryForm();
    } else {
      setFormData([]);
    }
  }, [props.selectCatalog]);

  const queryForm = () => {
    setFormData([]);
    setLoading(true);
    request('pmc/pcms/form/query', {
      data: { catalogId: props.selectCatalog.catalogId },
    }).then(res => {
      if (res && res.success == true && res.data) {
        setLoading(false);
        setFormData(res.data);
      } else if (res && res.errMessage) {
        message.error(res.errMessage);
      } else {
        message.error('查询失败');
      }
    });
  };

  const handleOk = () => {
    addFormEl.current.handleAdd().then(res => {
      if (res === true) {
        saveFormAddVisible(false);
        queryForm();
      }
    });
  };
  const handleCancel = () => {
    saveFormAddVisible(false);
  };

  const showModal = type => {
    saveFormAddVisible(true);
    saveFormAddType(type);
  };

  const showEditModal = () => {
    if (props.selectForm.formVersionId) {
      showModal('editVersion');
    } else {
      showModal('editForm');
    }
  };

  const handleUp = () => {
    Modal.confirm({
      content: `确认生效表单“${props.selectForm.formName}”版本“${parseFloat(
        props.selectForm.formVersionNbr
      ).toFixed(1)}”`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request('pmc/pcms/formVersion/update', {
          data: {
            formVersionId: props.selectForm.formVersionId,
            formId: props.selectForm.formId,
            statusCd: '1200',
          },
        }).then(res => {
          if (res && res.success === true) {
            message.success('生效成功');
            saveSelectForm({});
            saveFormButton(false);
            // queryForm();
            let selectFormTmp = props.selectForm;
            selectFormTmp.statusCdName = '生效';
            selectFormTmp.statusCd = '1200';
            updateFormData(selectFormTmp);
          } else if (res && res.errMessage) {
            message.error(res.errMessage);
          } else {
            message.error('生效失败');
          }
        });
      },
    });
  };

  const handleDown = () => {
    Modal.confirm({
      content: `确认失效表单“${props.selectForm.formName}”版本“${parseFloat(
        props.selectForm.formVersionNbr
      ).toFixed(1)}”`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request('pmc/pcms/formVersion/update', {
          data: {
            formVersionId: props.selectForm.formVersionId,
            statusCd: '1300',
          },
        }).then(res => {
          if (res && res.success === true) {
            message.success('失效成功');
            saveSelectForm({});
            saveFormButton(false);
            // queryForm();
            let selectFormTmp = props.selectForm;
            selectFormTmp.statusCdName = '失效';
            selectFormTmp.statusCd = '1300';
            updateFormData(selectFormTmp);
          } else if (res && res.errMessage) {
            message.error(res.errMessage);
          } else {
            message.error('失效失败');
          }
        });
      },
    });
  };

  const updateFormData = selectForm => {
    let formDataTmp = [...formData];
    formDataTmp.map(form => {
      if (form.children && form.children.length > 0) {
        form.children.map(formVersion => {
          if (selectForm.formVersionId === formVersion.formVersionId) {
            formVersion = { ...selectForm };
          } else if (selectForm.statusCd === '1200' && formVersion.statusCd === '1200') {
            // 将原表单下已生效的版本调整为失效
            formVersion.statusCd = '1300';
            formVersion.statusCdName = '失效';
          }
        });
      }
    });
    setFormData(formDataTmp);
  };

  const handleDelete = () => {
    let content = '';
    if (props.selectForm.formVersionId) {
      content = `确认删除表单“${props.selectForm.formName}”版本“${parseFloat(
        props.selectForm.formVersionNbr
      ).toFixed(1)}”`;
    } else {
      content = `确认删除表单“${props.selectForm.formName}”及其对应组件？`;
    }
    Modal.confirm({
      content,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        if (props.selectForm.formVersionId) {
          request('pmc/pcms/formVersion/delete', {
            method: 'GET',
            data: { formVersionId: props.selectForm.formVersionId },
          }).then(res => {
            if (res && res.success == true) {
              message.success('删除成功');
              saveSelectForm({});
              saveFormButton(false);
              queryForm();
            } else if (res && res.errMessage) {
              message.error(res.errMessage);
            } else {
              message.error('删除失败');
            }
          });
        } else {
          request('pmc/pcms/form/delete', {
            method: 'GET',
            data: { formId: props.selectForm.formId },
          }).then(res => {
            if (res && res.success == true) {
              message.success('删除成功');
              saveSelectForm({});
              saveFormButton(false);
              queryForm();
            } else if (res && res.errMessage) {
              message.error(res.errMessage);
            } else {
              message.error('删除失败');
            }
          });
        }
      },
    });
  };

  const handleAddVersion = () => {
    let addVersionNbr = 1;
    formData.map(form => {
      if (props.selectForm.formId === form.formId && form.children && form.children.length > 0) {
        form.children.map(formVersion => {
          const lastVersionNbr = parseFloat(formVersion.formVersionNbr);
          if (addVersionNbr < lastVersionNbr + 0.1) {
            addVersionNbr = (lastVersionNbr + 0.1).toFixed(1);
          }
        });
      }
    });
    saveAddVersionNbr(addVersionNbr);

    showModal('addVersion');
  };

  const handlePreView = () => {
    saveFormPreviewVisible(true);
  };

  const handleClosePreview = () => {
    saveFormPreviewVisible(false);
  };

  const handleDraw = () => {
    if (props.selectForm.statusCd !== '1000') {
      message.error(
        '只有锁定状态的版本才允许进行绘制，生效以及失效状态的版本只可进行预览，不支持绘制'
      );
      return;
    }
    saveFormDrawVisible(true);
  };

  const handleCopy = () => {
    if (props.selectForm.formVersionId !== null) {
      setLoading(true);
      request('pmc/pcms/formVersion/copy', {
        data: {
          formVersionId: props.selectForm.formVersionId,
        },
      })
        .then(res => {
          if (res && res.success === true) {
            message.success('复制成功');
            saveSelectForm({});
            saveFormButton(false);
            queryForm();
          } else if (res && res.errMessage) {
            message.error(res.errMessage);
          } else {
            message.error('复制失败');
          }
        })
        .always(() => {
          setLoading(false);
        });
    }
  };

  // 通过dva传递菜单列表数据，表单按钮使用
  const saveFormButton = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveFormButton`,
      payload: params,
    });
  };

  // 通过dva传递菜单列表数据，保存选择表单
  const saveSelectForm = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectForm`,
      payload: params,
    });
  };

  // 通过dva来保存当前的操作状态  值:true/false
  const saveFormAddVisible = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveFormAddVisible`,
      payload: params,
    });
  };

  // 通过dva来保存当前的操作状态  值:add/edit
  const saveFormAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveFormAddType`,
      payload: params,
    });
  };

  // 通过dva来保存当前的新增表单版本
  const saveAddVersionNbr = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveAddVersionNbr`,
      payload: params,
    });
  };

  // 通过dva来保存表单预览弹窗展示/隐藏标记
  const saveFormPreviewVisible = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveFormPreviewVisible`,
      payload: params,
    });
  };

  // 通过dva来保存表单绘制页面展示/隐藏标记
  const saveFormDrawVisible = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveFormDrawVisible`,
      payload: params,
    });
  };

  const customExpandIcon = props => {
    if (props.record.children) {
      if (props.expanded) {
        return (
          <span style={{ marginRight: 4 }}>
            <a
              style={{ color: 'black', marginRight: 8 }}
              onClick={e => {
                props.onExpand(props.record, e);
              }}
            >
              <Icon type="minus-square" style={{ fontSize: 16 }} />
            </a>
            <Icon type="folder-open" style={{ fontSize: 16 }} />
          </span>
        );
      }
      return (
        <span style={{ marginRight: 4 }}>
          <a
            style={{ color: 'black', marginRight: 8 }}
            onClick={e => {
              props.onExpand(props.record, e);
            }}
          >
            <Icon type="plus-square" style={{ fontSize: 16 }} />
          </a>
          <Icon type="folder" style={{ fontSize: 16 }} />
        </span>
      );
    }
    return (
      <span style={{ marginRight: 4 }}>
        <Icon type="file" style={{ fontSize: 16 }} />
        &nbsp;
      </span>
    );
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'formName',
      render: (text, record) => {
        return record.formVersionId ? parseFloat(record.formVersionNbr).toFixed(1) : text;
      },
    },
    {
      title: '编码',
      dataIndex: 'formCode',
      render: (text, record) => (record.formVersionId ? '' : text),
    },
    {
      title: '状态',
      dataIndex: 'statusCdName',
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null),
    },
    {
      title: '描述',
      dataIndex: 'formDesc',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: (text, record) => (
        <Tooltip placement="topLeft" title={record.formVersionId ? record.formVersionDesc : text}>
          {record.formVersionId ? record.formVersionDesc : text}
        </Tooltip>
      ),
    },
  ];

  return (
    <Spin spinning={loading}>
      <div style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          className="margin-right"
          disabled={!props.catalogButton}
          onClick={() => showModal('addForm')}
        >
          新增表单
        </Button>
        {/* <Button className="margin-right" disabled={!props.formButton || !props.selectForm.formVersionId}>
          导入
        </Button> */}
        <Button
          className="margin-right"
          disabled={!props.formButton || !props.selectForm.formVersionId}
          onClick={handleDraw}
        >
          绘制
        </Button>
        <Button
          className="margin-right"
          disabled={!props.formButton || !props.selectForm.formVersionId}
          onClick={handleUp}
        >
          生效
        </Button>
        <Button
          className="margin-right"
          disabled={!props.formButton || !props.selectForm.formVersionId}
          onClick={handleDown}
        >
          失效
        </Button>
        <Button
          className="margin-right"
          disabled={!props.formButton || !props.selectForm.formVersionId}
          onClick={handlePreView}
        >
          预览
        </Button>
        <Button
          className="margin-right"
          disabled={!props.formButton || !props.selectForm.formVersionId}
          onClick={handleCopy}
        >
          复制表单版本
        </Button>
        {/* <Link to={`/formDesigner/templates/flow?formVersionId=${props.selectForm.formVersionId}&objInstId=1&objType=2&mode=readOnly`}>预览</Link> */}
        <Button className="margin-right" disabled={!props.formButton} onClick={handleAddVersion}>
          新增表单版本
        </Button>
        <Button className="margin-right" disabled={!props.formButton} onClick={showEditModal}>
          修改
        </Button>
        <Button
          type="danger"
          className="margin-right"
          disabled={!props.formButton}
          onClick={handleDelete}
        >
          删除
        </Button>
      </div>
      <Table
        rowKey={record => {
          if (record.formVersionId) {
            return record.formVersionId;
          }
          return record.formId;
        }}
        columns={columns}
        pagination={false}
        dataSource={formData}
        onRow={record => {
          return {
            onClick: () => {
              if (record.formVersionId) {
                if (record.formVersionId === props.selectForm.formVersionId) {
                  saveSelectForm({});
                  saveFormButton(false);
                } else {
                  saveSelectForm(record);
                  saveFormButton(true);
                }
              } else if (record.formId) {
                if (record.formId === props.selectForm.formId && !props.selectForm.formVersionId) {
                  saveSelectForm({});
                  saveFormButton(false);
                } else {
                  saveSelectForm(record);
                  saveFormButton(true);
                }
              }
            },
          };
        }}
        rowClassName={record => {
          if (record.formVersionId) {
            return record.formVersionId === props.selectForm.formVersionId
              ? styles.clickRowStyl
              : '';
          }
          if (record.formId && !props.selectForm.formVersionId) {
            return record.formId === props.selectForm.formId ? styles.clickRowStyl : '';
          }
          return '';
        }}
        expandIcon={props => customExpandIcon(props)}
      />
      {/* 新增表单/表单版本 */}
      <Modal
        title={formAddTitle}
        visible={props.formAddVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="70%"
        destroyOnClose
      >
        <AddForm cRef={addFormEl} />
      </Modal>
      {/* 表单版本预览 */}
      <Modal
        title="预览"
        visible={props.formPreviewVisible}
        onOk={handleClosePreview}
        onCancel={handleClosePreview}
        width="70%"
        destroyOnClose
      >
        <Flow2 formVersionId={props.selectForm.formVersionId} />
      </Modal>
    </Spin>
  );
}
export default connect(({ formManage }) => ({
  selectCatalog: formManage.selectCatalog,
  selectForm: formManage.selectForm,
  formAddVisible: formManage.formAddVisible,
  formAddType: formManage.formAddType,
  catalogButton: formManage.catalogButton,
  formButton: formManage.formButton,
  formPreviewVisible: formManage.formPreviewVisible,
  formDrawVisible: formManage.formDrawVisible,
}))(Form.create({})(FormInfo));
